package com.asp.aspchain.tstaccount.service;

import com.alibaba.fastjson.JSON;
import com.asp.aspchain.core.dao.TocAccountMapper;
import com.asp.aspchain.core.ethereum.EthService;
import com.asp.aspchain.core.model.TocAccountModel;
import com.asp.aspchain.core.util.AjaxResult;
import com.asp.aspchain.tstaccount.constants.ErrorCode;
import com.asp.aspchain.tstaccount.request.QryAccountReq;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

@Service
public class EoaQuebalService {

	private final static Logger logger = Logger.getLogger(EoaQuebalService.class);
	@Autowired
	TocAccountMapper tocAccountMapper;
	@Autowired
	EthService ethService;

	public AjaxResult ecoQueryBalance(String json) {

		QryAccountReq accountReq = JSON.parseObject(json, QryAccountReq.class);
		String accountid = accountReq.getAccountid();
		BigInteger balance = null;
		try {
			balance = ethService.getBalance(accountid);
		} catch (IOException e) {
			logger.info("tst查询账户发生错误");
			e.printStackTrace();
			return new AjaxResult(ErrorCode.QUERY_FAIL, "tst查询账户发生错误", "tst查询账户发生错误");
		}
		
		//查询到的余额与本地的信息不一致则更新
		TocAccountModel tocAccountModel = tocAccountMapper.selectById(accountid);
		if(balance.compareTo(tocAccountModel.getTokenvalue()) != 0) {
			tocAccountModel.setTokenvalue(balance);
			tocAccountMapper.updateById(tocAccountModel);
		}
		
		// 返回响应
		Map<String, String> resp = new HashMap<>();
		resp.put("status", tocAccountModel.getStatus());
		resp.put("tokentype", tocAccountModel.getTokentype());
		resp.put("tokenvalue", balance.toString());

		return new AjaxResult(ErrorCode.SUCCESS, "tst获取账户信息成功", resp, "tst获取账户信息成功");
	}

}
